package com.hnevc.listviewdemo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    //control
    private Button mBtnAddFood;
    private Button mBtnArrayAdapter;
    private Button mBtnSimpleAdapter;
    private Button mBtnCursorAdapter;
    private Button mBtnShowFood;
    private ListView mListView;

    //data
    private String[] mFoodNames;
    private String[] mFoodPirces;
    private TypedArray mTypedArray;
    private String[] mFoodDescs;
    //食品列表
    private List<Food> mFoodList;
    private MyBaseAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initEvent();
    }


    //初始化视图控件
    private void initView() {
        //mBtnBaseAdapter = (Button) findViewById(R.id.id_btn_base_adapter);
        mBtnAddFood = (Button) findViewById(R.id.id_btn_add_food);
        mBtnArrayAdapter = (Button) findViewById(R.id.id_btn_array_adapter);
        mBtnSimpleAdapter = (Button) findViewById(R.id.id_btn_simpel_adapter);
        mBtnCursorAdapter = (Button) findViewById(R.id.id_btn_cursor_adapter);
        mBtnShowFood = (Button) findViewById(R.id.id_btn_food_adapter);
        //获取布局文件中的控件
        mListView = (ListView) findViewById(R.id.id_lv_base);


    }

    //初始化数据
    private void initData() {
       //TODO 创建线程，访问网络，获取数据，构建mFoodList
        new Thread(new Runnable() {
            @Override
            public void run() {
                //1 构建OKHttpClient对象
                //OkHttpClient client = new OkHttpClient();
                OkHttpClient client = new OkHttpClient.Builder()
                        .cookieJar(new MyCookieJar())
                        .build();
                //3 构建Request对象
                Request request = new Request.Builder()
                        .url("http://"+getServerIp()+":8080/RestaurantServer/Food/getFoods")
                        .get()
                        .build();
                try {
                    //4 发送请求,获取响应
                    Response response = client.newCall(request).execute();
                    String data = response.body().string();
                    Log.e(TAG, "run: "+data );
                    //解析
                    Gson gson = new Gson();
                    mFoodList = gson.fromJson(data, new TypeToken<List<Food>>() {}.getType());


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    //设置控件的事件处理
    private void initEvent()
    {
        mBtnAddFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击按钮跳转到AddFoodActivity
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddFoodActivity.class);
                startActivity(intent);
            }
        });
        mBtnShowFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter = new MyBaseAdapter();
                mListView.setAdapter(mAdapter);
            }
        });

        mBtnCursorAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mBtnSimpleAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mBtnArrayAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });



    }

    //自定义数据适配器
    class MyBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mFoodList.size();
        }

        @Override
        public Object getItem(int position) {
            return mFoodList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //TODO 修改getView使得所获取的数据都能显示出来

            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.food_list_item, null);

            TextView mTvFoodName = (TextView) view.findViewById(R.id.id_tv_foodName);
            TextView mTvFoodPrice = (TextView) view.findViewById(R.id.id_tv_foodPrice);
            ImageView mIvFoodPic = (ImageView) view.findViewById(R.id.id_iv_foodPic);
            TextView mTvFoodDesc = (TextView) view.findViewById(R.id.id_tv_foodDesc);

            Food food = mFoodList.get(position);
            mTvFoodName.setText(food.getFoodName());
            mTvFoodDesc.setText(food.getFoodDesc());
            mTvFoodPrice.setText(food.getFoodPrice());

            //构建图片URL地址
            String imageUrl ="http://"+getServerIp()+":8080/RestaurantServer/uploadFoodImage/"
                    +food.getFoodPic();
            Picasso.with(MainActivity.this)// Picasso 的上下文环境，在哪里显示？
                    .load(imageUrl) //Picasso要加载的图片的地址？
                    .into(mIvFoodPic); //Picasso要显示图片的视图是谁？
            //mIvFoodPic.setImageResource(food.getDrawable());
            return view;
        }
    }

    private String getServerIp() {
        //获取SP对象
        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
        //获取sp中的key为serverip的值
        String serverip = sp.getString("serverip", null);
        //返回获取到的数据
        return serverip;
    }
}
